//
//  PopoverAdressController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/31.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit

class PopoverAdressController: BaseViewController {
    
    var myCollectionView : UICollectionView?
    
    var bottomLineView : UIView?
    
    var dataModels : [ProvinceModel]!
    
    var selectProvinceModel : ProvinceModel?
    
    var selectCityModel : CityModel?

    var selectDistrictModel : DistrictModel?

    var topModels = [String]()
    
    var bottomModels = [String]()
    
    var block : ((_ model : DistrictModel?,_ model2 : CityModel? ) -> ())?

    lazy var topView : UIView = {
        
        let temp = UIView(frame: CGRect(x: 0, y: 0, width: KScreenW, height: 44))
        
        temp.backgroundColor = UIColor.white
        
        let label = UILabel()
        
        label.frame = temp.bounds
        
        label.text = "所在地区"
        
        label.font = UIFont.systemFont(ofSize: 16)
        
        label.textAlignment = .center
        
        temp.addSubview(label)
        
        
        
        let btn = LightDisableBtn(type: .custom)
        
        btn.frame = CGRect(x: KScreenW - 46, y: 0, width: 46, height: 44)
        
        btn.setImage(UIImage(named: "jshop_list_cancel_normal"), for: .normal)
        
        btn.addTarget(self, action: #selector(dissmissBtnDidTap), for: .touchUpInside)
        
        temp.addSubview(btn)
        
        return temp
        
    }()

    
    lazy var middleView : UIView = {
        
        let temp = UIView(frame: CGRect(x: 0, y: 44, width: KScreenW, height: 41))
        
        temp.backgroundColor = UIColor.white
        
        
        let topLineView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenW, height: 0.5))
        
        topLineView.backgroundColor = UIColor.lineGray()
        
        temp.addSubview(topLineView)
        
        let collet = UICollectionView(frame:CGRect(x: 0, y: 0.5, width: KScreenW, height: 40), collectionViewLayout: PopoverFlowLayout())
        
        collet.dataSource = self
        
        collet.delegate = self
        
        collet.backgroundColor = UIColor.white
        
        self.myCollectionView = collet
        
        collet.register(UINib(nibName: self.StringFromClass(classType: PopoverMyCollCell.self), bundle: nil), forCellWithReuseIdentifier: PopoverMyCollCell.identifer())

        temp.addSubview(collet)
        
        
        let bottomLineView = UIView(frame: CGRect(x: 0, y: 40.5, width: KScreenW, height: 0.5))
        
        bottomLineView.backgroundColor = UIColor.lineGray()
        
        temp.addSubview(bottomLineView)
        
        
        let lineView = UIView(frame: CGRect(x: 12, y: 39, width: 0, height: 2))
        
        self.bottomLineView = lineView
        
        lineView.backgroundColor = UIColor.selectTextColor()
        
        temp.addSubview(lineView)


        return temp
        
    }()
    
    
    
    lazy var tableView : BaseTableView = {
        
        let temp = BaseTableView(frame: CGRect(x: 0, y: 85, width: KScreenW, height: 245), style: .plain)
        
        temp.delegate = self
        
        temp.dataSource = self
        
        temp.showsVerticalScrollIndicator = false
        
        temp.showsHorizontalScrollIndicator = false
        
        temp.allowsSelection = true
        
        temp.backgroundColor = UIColor.white
        
        temp.register(UINib(nibName: self.StringFromClass(classType: PopoverMyTableCell.self), bundle: nil), forCellReuseIdentifier: PopoverMyTableCell.identifer())

        
         return temp
        
    }()
    
    
    



    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.purple
        
        topModels.append("请选择")
        
        view.addSubview(topView)
        view.addSubview(middleView)
        view.addSubview(tableView)
        
        bottomLineView?.frame.size.width = getLabelW(str: "请选择")
        
       
        
        



        

    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        if dataModels != nil {
            for tempProvinceModel in dataModels {
                tempProvinceModel.isSelect = false
                for tiModel in tempProvinceModel.citys {
                    tiModel.isSelect = false
                    for disModel in tiModel.districts {
                        disModel.isSelect = false
                    }
                }
            }
        }
    }
    
    
    


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func dissmissBtnDidTap() {
        dismiss(animated: true, completion: nil)
    }
    
    
    func animei() {
        
     tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
        
     let index = IndexPath(item: topModels.count - 1, section: 0)
        
        
        if let temp  = myCollectionView?.cellForItem(at: index) as? PopoverMyCollCell {
            
            
            let label = temp.rightLabel
            
            let w  = getLabelW(str: label!.text!)
            
            
            
            UIView.animate(withDuration: 0.5, animations: {
                //            self.underline?.frame.size.width = KScreenW / CGFloat(self.childViewControllers.count)
                
                self.bottomLineView?.frame.size.width = w

                self.bottomLineView?.center.x = temp.center.x + label!.center.x - (temp.frame.size.width * 0.5)
                
                
                
            }) { (_) in
                
                
                if self.topModels.count == 3{
                    
                    if self.topModels[2] != "请选择"{
                        
                        self.perform(#selector(self.dissMiss), with: nil, afterDelay: 0.25)
                    
                    
                        
                    }
                
                  
                
                }
                
                
                
                if self.topModels.count == 2 && self.topModels[1] != "请选择"{
                
                    if self.selectCityModel!.districts.count < 1{
                        self.perform(#selector(self.dissMiss), with: nil, afterDelay: 0.25)

                    }
                
                
                }
                
                
                

                
                
            }
            

        }
        
        
        
    }
    
    
    func dissMiss() {
        
//        QL1(Thread.current)
        
        if self.topModels.count == 2 && self.selectCityModel!.districts.count < 1 && self.topModels[1] != "请选择"{
        
        
            block!(nil,selectCityModel)

        
        }else{
        
            if block != nil && selectDistrictModel != nil {
                
                block!(selectDistrictModel!,nil)
                
            }

        
        }
        
        
        
        self.dismiss(animated: true, completion: {
            
            
        })
        

    }
    

    
    deinit {
        QL1("消失了-----")
    }


}




extension PopoverAdressController:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        return topModels.count


        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PopoverMyCollCell.identifer(), for: indexPath) as! PopoverMyCollCell
        
        if indexPath.item == topModels.count - 1 {
            cell.isLast = true
        } else {
            cell.isLast = false
        }
        
        cell.text = topModels[indexPath.item]

        
        return cell
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        if indexPath.item == 0 {
            if topModels[0] != "请选择" {
            
//                selectProvinceModel?.isSelect = false
                selectCityModel?.isSelect = false
                selectDistrictModel?.isSelect = false
//                selectProvinceModel = nil
                selectCityModel = nil
                selectDistrictModel = nil
                
                topModels.removeAll()
                
                topModels.append(selectProvinceModel!.province_name)

            
            
            }
           
            
            
        } else if indexPath.item == 1{
            
            if topModels[1] != "请选择" {
                
                selectDistrictModel?.isSelect = false
//                selectCityModel?.isSelect = false
//                selectCityModel = nil
                selectDistrictModel = nil
                topModels.removeAll()
                topModels.append(selectProvinceModel!.province_name)
                topModels.append(selectCityModel!.city_name)
                

            }
            
            
        }else{
        
        
        
        }
        
        
        tableView.reloadData()
        myCollectionView?.reloadData()
        myCollectionView?.layoutIfNeeded()
        animei()
        
        
      QL1(topModels[indexPath.item])
}

    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        
        let str = topModels[indexPath.item]
        
        let lableW = getLabelW(str: str)
        
        return CGSize(width: lableW + 15, height:40)
    }
    
    
    
    func getLabelW(str : String) -> CGFloat {
        
        let rect = CGRect(x: 0, y: 0, width: CGFloat(MAXFLOAT), height: 40)
        
        let attrbute = [NSFontAttributeName:UIFont.systemFont(ofSize: 15)]

        return  str.boundingRect(with: rect.size, options: [.usesLineFragmentOrigin,.usesFontLeading,.truncatesLastVisibleLine], attributes: attrbute, context: nil).size.width

    }

}







// MARK:- tableview代理方法
extension PopoverAdressController{
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
      return 1
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if topModels.count == 1 {
            
            return dataModels.count
            
        } else if topModels.count == 2 {
            
            return selectProvinceModel?.citys.count ?? 0
            
        }else{
            
            return selectCityModel?.districts.count ?? 0
            
        }
        
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let tableCell : PopoverMyTableCell =  tableView.dequeueReusableCell(withIdentifier: PopoverMyTableCell.identifer()) as! PopoverMyTableCell
        
        
        if topModels.count == 1 {
            
            let model = dataModels[indexPath.row]
            
            tableCell.nameStr = model.province_name
            
            tableCell.isSelect = model.isSelect
            
        } else if topModels.count == 2 {
            
            let model = selectProvinceModel?.citys[indexPath.row]
            
            tableCell.nameStr = model?.city_name
            
            tableCell.isSelect = model?.isSelect ?? false
            
        }else{
            
            let model = selectCityModel?.districts[indexPath.row]
            
            tableCell.nameStr = model?.district_name
            
            
            tableCell.isSelect = model?.isSelect ?? false
            
        }
        

        
        
        
        
        return tableCell
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 35
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        

        
        if topModels.count == 1 {
            
            let model = dataModels[indexPath.row]
            
            selectProvinceModel?.isSelect = false
            
            
            selectProvinceModel = model
            
            
            model.isSelect = true
            
            topModels.removeAll()
            
            topModels.append(model.province_name)
            topModels.append("请选择")
            
        

            
        } else if topModels.count == 2 {
            
            let model = selectProvinceModel?.citys[indexPath.row]
            
            selectCityModel?.isSelect = false
            
            selectCityModel = model
            
            model?.isSelect = true
            topModels.removeAll()
            
            topModels.append(selectProvinceModel!.province_name)
            topModels.append(selectCityModel!.city_name)
            
            if selectCityModel!.districts.count > 0 {
                
                topModels.append("请选择")

            } else {
                
                
                
            }

      
          
            
   
            
        }else{
            
            let model = selectCityModel?.districts[indexPath.row]
            
            
            selectDistrictModel?.isSelect = false
            
            selectDistrictModel = model
            
            model?.isSelect = true
            
            topModels.removeAll()

            topModels.append(selectProvinceModel!.province_name)
            topModels.append(selectCityModel!.city_name)
            topModels.append(selectDistrictModel!.district_name)

            
        }
        
        tableView.reloadData()
        myCollectionView?.reloadData()
        myCollectionView?.layoutIfNeeded()
        animei()
        
//        myCollectionView?.performBatchUpdates({
//            IndexSet(
//            self.myCollectionView?.reloadSections(<#T##sections: IndexSet##IndexSet#>)
//            
//        }, completion: { (_) in
//            
//            self.animei()
//  
//        })
        
        

        
    }
    
    
    
}








class PopoverFlowLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        
        
    }
    
    
}
